FROM golang:1.20-alpine AS frontend-builder

# 安装前端构建所需依赖
RUN apk add --no-cache nodejs npm

# 设置 npm 淘宝镜像源和其他优化
RUN npm config set registry https://registry.npmmirror.com && \
    npm config set cache /root/.npm && \
    npm config set fund false && \
    npm config set progress false && \
    npm config set loglevel warn && \
    npm config set audit false && \
    npm config set fetch-retries 5 && \
    npm config set fetch-retry-mintimeout 20000 && \
    npm config set fetch-retry-maxtimeout 120000

# 只复制前端相关文件，避免后端文件变化导致缓存失效
WORKDIR /app
COPY web/frontend/package*.json /app/web/frontend/
WORKDIR /app/web/frontend
RUN npm ci --no-audit --prefer-offline

# 仅复制前端源代码
COPY web/frontend/ ./

# 构建前端
ENV NODE_ENV=production
RUN npm run build

FROM golang:1.20-alpine AS backend-builder

WORKDIR /app

# 设置 Go 模块代理
ENV GOPROXY=https://goproxy.cn,direct
# 配置Go构建缓存
ENV GOCACHE=/go-cache

# Copy go module files first for better caching
COPY go.mod go.sum* ./
RUN go mod download

# 直接复制整个代码库
COPY . .

# 复制已构建的前端文件
COPY --from=frontend-builder /app/web/frontend/dist /app/web/frontend/dist

# 构建Go应用 - 移除了-a标志以使用缓存，加快构建速度
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o go-ddns .

# 最终镜像
FROM alpine:latest

WORKDIR /app

# 使用国内 Alpine 镜像源
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories

# Install CA certificates for HTTPS requests
RUN apk --no-cache add ca-certificates

# Copy the binary from the builder stage
COPY --from=backend-builder /app/go-ddns /app/go-ddns

# 复制已构建的前端文件
COPY --from=frontend-builder /app/web/frontend/dist /app/web/frontend/dist

# Create a directory for the config
RUN mkdir -p /app/config
# Create a directory for the logs
RUN mkdir -p /app/logs

# Tell Docker to use these directories
VOLUME ["/app/config", "/app/logs"]

# 添加健康检查
HEALTHCHECK --interval=30s --timeout=10s --retries=3 CMD wget -q --spider http://localhost:8080 || exit 1

# Set the entrypoint
ENTRYPOINT ["/app/go-ddns"] 